package com.bayi.storage.utils;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class GridSpaceDecoration extends RecyclerView.ItemDecoration {

    //间距
    private int mSpace;

    public GridSpaceDecoration(int dpValue) {
        this.mSpace = UIUtil.dp2px(dpValue);
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager();

        //获取每行的个数
        int spanCount = manager.getSpanCount();
        //获取当前位置
        int position = parent.getChildAdapterPosition(view);
        //当前列
        int column = position % spanCount;

        //计算垂直方向上的间距，当不是首行时
        if (position >= spanCount) {
            //添加垂直方向上的间距
            outRect.top = mSpace;
        }

        //计算水平方向的间距
        outRect.left = column * mSpace / spanCount; // column * ((1f / spanCount) * spacing)
        outRect.right = mSpace - (column + 1) * mSpace / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
    }
}
 